import config from '../config/index.js'
import { setStorage, getStorage, removeStorage } from './customStorage.js'
import api from '../api/index.js'
import aes from '../plugin/aes.js'
import cookies from "vue-cookies"
import { Message } from 'element-ui';


export const USERINFO_KEY = 'cloud_userinfo'
export const Permissions_KEY = 'cloud_permissions'

export const aesEncryption = (data) => {
    return aes.encryption(data, config.aes.key);
}

export const getToken = () => {
    let storageValue = getStorage(config.cookies.key);
    if (storageValue) {
        return storageValue;
    } else {
        storageValue = cookies.get(config.cookies.key);
    }
    return storageValue;
}

export const setToken = token => {
    if (!token) {
        removeStorage(config.cookies.key)
        return
    }
    cookies.set(config.cookies.key, token, "30d", "/", config.cookies.domain);
    setStorage(config.cookies.key, token)
}
export const clearStore = () => {
    removeStorage(config.cookies.key);
    removeStorage(USERINFO_KEY);
    cookies.remove(config.cookies.key);
}
export const getUserInfo = () => {
    let userInfo = null
    let userInfoStr = getStorage(USERINFO_KEY);
    if (userInfoStr) {
        userInfo = JSON.parse(aes.decryption(userInfoStr, config.aes.key))
    } else {

    }
    return userInfo
}

export const getPermissions = async () => {
    let rePerms = null;
    let res = await api.getUserInfo({});
    if (res.success) {
        let instance = res.instance;
        rePerms = instance.permissions;
        setStorage(USERINFO_KEY, aes.encryption(JSON.stringify(instance), config.aes.key));
    } else {
        Message.error({
            message: '获取用户信息异常，请联系管理员'
        });
    }
    return rePerms;
}
export const setUserInfo = async token => {
    if (token) {
        await api.getUserInfo({}).then(res => {
            if (res.success) {
                let instance = res.instance;
                setStorage(USERINFO_KEY, aes.encryption(JSON.stringify(instance), config.aes.key));
            } else {
                Message.error({
                    message: '获取用户信息异常，请联系管理员'
                });
            }
        })
    } else {
        removeStorage(USERINFO_KEY);
        cookies.remove(config.cookies.key);
    }
}

export const getNewToken = async orgCode => {
    let newToken = null;
    let res = await api.changeToken({ organizationCode: orgCode });
    if (res.success) {
        newToken = res.instance.token;
        setToken(newToken);
        return res.instance;
    } else {
        Message.error({ message: res.errorMsg });
        return newToken;
    }
}
